//
//  ThreeViewController.m
//  WeiMo
//
//  Created by weixian he on 12-8-18.
//  Copyright (c) 2012年 . All rights reserved.
//

#import "ThreeViewController.h"

#import "ThreeImageCell.h"
#import "UIImageView+WebCache.h"
#import "SVPullToRefresh.h"

#import "AGIPCToolbarItem.h"
#import "ALAsset+AGIPC.h"
#import "TwoImageCell.h"
#import "DLog.h"
#import "SecondViewController.h"
#import "SDImageCache.h"
#import "JSONKit.h"
#import "InterfaceDefine.h"
#import "FMManager.h"
#import "BDKNotifyHUD.h"
#import "LoginViewController.h"
#import "ProductAroundCell.h"
#import "ProductShowWebViewController.h"


#define kImageIntNums 3

#define kFirstPageSize (@"12")
#define kOtherPageSize (@"12")

@interface ThreeViewController ()
{
    int mCurPage;
    bool mIsLastPage;
    bool mIsUpdate;
    MBProgressHUD *mThreeViewHUD;
    NSString *mUserSelfId;
    NSString *mUserParentId;
}

@property (nonatomic,retain) UITableView *firstTableView;
@property(nonatomic,copy) NSString *allPageCount;
@property (strong, nonatomic) BDKNotifyHUD *notify;
@property(nonatomic,retain) NSTimer *timer;
@property (nonatomic,retain) FirstViewPullToGetMoreDataCell *getMoreDataCell;

@property (nonatomic,retain) NSMutableArray *secondMenuDatas;
@property (nonatomic,retain) UIButton *rightLoginBarButton;
@property (nonatomic,retain) UIButton *rightSecondMenuButton;

@property (nonatomic,retain) CustomPopoverView *secondMenuShowView;

@property (nonatomic,retain) NSString *modelTypeFlag;   //一级目录id
@end

@implementation ThreeViewController
@synthesize list;
@synthesize selectedPhotos;
@synthesize imagePickerController;
@synthesize homeItemArray;
@synthesize allPageCount;
@synthesize timer;
@synthesize delegate;
@synthesize slideBarDisappearButton;
@synthesize firstTableView;
@synthesize getMoreDataCell;
@synthesize secondMenuDatas;
@synthesize rightLoginBarButton,rightSecondMenuButton;
@synthesize secondMenuShowView;
@synthesize modelTypeFlag;

#pragma mark - system methods

-(void)dealloc
{
    DEnter();
    self.list = nil;
    self.imagePickerController = nil;
    self.selectedPhotos = nil;
    self.homeItemArray = nil;
    self.allPageCount = nil;
    self.delegate = nil;
    [self.timer invalidate];
    self.timer = nil;
    self.slideBarDisappearButton = nil;
    self.firstTableView = nil;
    self.getMoreDataCell = nil;
    self.secondMenuDatas = nil;
    self.rightLoginBarButton = nil;
    self.rightSecondMenuButton = nil;
    self.secondMenuShowView = nil;
    self.modelTypeFlag = nil;
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        self.title = NSLocalizedString(@"微模", @"Home");
        self.tabBarItem.image = [UIImage imageNamed:@"weimohome"];
    }
    return self;
}

- (void)viewDidLoad
{
    DEnter();
    [super viewDidLoad];
    
    self.modelTypeFlag = @"1";
    mIsLastPage = false;
    mIsUpdate = false;
    [self.view setBackgroundColor:[UIColor colorWithWhite:1.0 alpha:0.8]];
    KeyValueObject *firstMenu = [[FMManager sharedInstance] firstMenuItemFlag];
    mUserParentId = firstMenu.key;
    self.navigationController.navigationBar.topItem.title = firstMenu.keyDispName;
    mUserSelfId = [[FMManager sharedInstance] secondMenuItemFlag];
    
    UIImage *slideImage = [UIImage imageNamed:@"slideBar.png"];
    UIButton *slideBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    slideBtn.bounds = CGRectMake( 0, 0, slideImage.size.width, slideImage.size.height );
    [slideBtn setImage:slideImage forState:UIControlStateNormal];
    [slideBtn addTarget:self action:@selector(leftSlideBarItemClickedEvent) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftSlideBarItem = [[[UIBarButtonItem alloc] initWithCustomView:slideBtn] autorelease];
    self.navigationItem.leftBarButtonItem = leftSlideBarItem;
    
    UIImage *faceImage = [UIImage imageNamed:@"loginbtn.png"];
    self.rightLoginBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightLoginBarButton.bounds = CGRectMake( 0, 0, faceImage.size.width, faceImage.size.height );
    [self.rightLoginBarButton setImage:faceImage forState:UIControlStateNormal];
    
    faceImage = [UIImage imageNamed:@"secondMenu.png"];
    self.rightSecondMenuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightSecondMenuButton.bounds = CGRectMake( 0, 0, faceImage.size.width, faceImage.size.height );
    [self.rightSecondMenuButton setImage:faceImage forState:UIControlStateNormal];
    [self.rightSecondMenuButton addTarget:self action:@selector(showSecondMenuBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    //设置rightBarButtonItem
    [self setRightBarButton];
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect.size.height = rect.size.height - 20 - 44 - 49;
    self.firstTableView = [[[UITableView alloc] initWithFrame:rect] autorelease];
    self.firstTableView.backgroundColor = [UIColor clearColor];
    self.firstTableView.dataSource = self;
    self.firstTableView.delegate = self;
    self.firstTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.firstTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.firstTableView];
    
    self.homeItemArray = nil;
    [self.firstTableView.pullToRefreshView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    //上拉事件
    [self.firstTableView addPullToRefreshWithActionHandler:^{
        mCurPage=1;
        mIsUpdate = true;
        //mCurPage = mCurPage + 5;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getKindDatasOfThreeView) userInfo:nil repeats:NO];

    }];
    
    self.slideBarDisappearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.slideBarDisappearButton.frame = rect;
    [self.slideBarDisappearButton addTarget:self action:@selector(slideBarDisappearButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.slideBarDisappearButton addTarget:self action:@selector(slideBarDisappearButtonEvent) forControlEvents:UIControlEventTouchDragEnter];
    [self.view addSubview:self.slideBarDisappearButton];
    self.slideBarDisappearButton.hidden = YES;
}

- (void)viewDidUnload
{
    DEnter();
    [super viewDidUnload];
    self.list = nil;
    self.homeItemArray = nil;
    self.allPageCount = nil;
    [self.timer invalidate];
    self.timer = nil;
}

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if(self.homeItemArray == nil)
    {
        mIsLastPage = false;
        mCurPage = 1;
        
        mThreeViewHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mThreeViewHUD];
        mThreeViewHUD.delegate = self;
        [self getKindDatasOfThreeView];
        [mThreeViewHUD show:YES];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)didReceiveMemoryWarning
{
    DEnter();
    [[SDImageCache sharedImageCache] clearMemory];
    [super didReceiveMemoryWarning];
}

#pragma mark - private methods

//设置右侧bar按钮
- (void)setRightBarButton
{
    if ([self.navigationController.navigationBar.topItem.title isEqualToString:@"首页"])
    {
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightLoginBarButton];
        [self.rightLoginBarButton addTarget:self action:@selector(editAction:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = rightButtonItem;
        [rightButtonItem release];
    }
    else
    {
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightSecondMenuButton];
        self.navigationItem.rightBarButtonItem = rightButtonItem;
        [rightButtonItem release];
    }
}

//请求数据
-(void)getKindDatasOfThreeView
{
    NSMutableDictionary *dic = [[[NSMutableDictionary alloc] init] autorelease];
    [dic setObject:[NSString stringWithFormat:@"%d",mCurPage] forKey:@"startPage"];
    if(mCurPage == 1)
    {
        [dic setObject:kFirstPageSize forKey:@"pageSize"];
    }
    else
    {
        [dic setObject:kOtherPageSize forKey:@"pageSize"];
    }
    [dic setValue:mUserParentId forKey:@"parentId"];
    [dic setValue:mUserSelfId forKey:@"selfId"];
    NSString *postStr = [dic JSONString];
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@",kHttpHost,kGetHomeData];
    DLog(@"url:%@,post:%@",urlStr,postStr);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    request.delegate = self;
    request.timeOutSeconds = 60;
    [request startAsynchronous];
}

//判断是不是‘周边商品’模块
- (BOOL)judgeFirstTitleIsOrNotProductaround
{
    BOOL result = NO;
    //NSString *string = self.navigationController.navigationBar.topItem.title;
    if ([self.modelTypeFlag isEqualToString:@"999"])    //周边商品
    {
        result = YES;
    }
    
    return result;
}

#pragma mark - proteced methods

//清空列表数据
- (void)releaseTableViewDatas
{
    self.homeItemArray = nil;
    [self.firstTableView reloadData];
}

//根据侧边栏选项刷新数据
- (void)refreshTitleAndDatas:(KeyValueObject *)values
{
    self.navigationController.navigationBar.topItem.title = values.keyDispName;
    mUserParentId = values.value;
    mUserSelfId = values.key;
    mCurPage = 1;
    
    if ([values.key isEqualToString:@"161"])    //经纪人
    {
        self.modelTypeFlag = @"3";
    }
    else if ([values.key isEqualToString:@"181"])   //企业
    {
        self.modelTypeFlag = @"4";
    }
    else if ([values.key isEqualToString:@"999"])   //周边商品
    {
        self.modelTypeFlag = @"999";
    }
    else                                            //其他
    {
        self.modelTypeFlag = @"1";
    }
    
    [self getKindDatasOfThreeView];
    
    //组装二级目录数据
    if (self.secondMenuDatas)
    {
        [self.secondMenuDatas removeAllObjects];
        self.secondMenuDatas = nil;
    }
    
    self.secondMenuDatas = [[[NSMutableArray alloc] init] autorelease];
    
    NSMutableArray *secondMenus = [FMManager getMenuDatasOfChoosedFirstMenu:values.key];
    for (int i=0; i<secondMenus.count; i++)
    {
        NSDictionary *dic = [secondMenus objectAtIndex:i];
        KeyValueObject *item = [[KeyValueObject alloc] init];
        item.key = [dic objectForKey:@"selfId"];
        item.value = [dic objectForKey:@"parentId"];
        item.keyDispName = [dic objectForKey:@"name"];
        [self.secondMenuDatas addObject:item];
        [item release];
    }
    
    if ([values.keyDispName isEqualToString:@"首页"] || self.secondMenuDatas.count > 0)
    {
        [self setRightBarButton];
        
        if (self.secondMenuDatas.count > 0)
        {
            KeyValueObject *item = [[KeyValueObject alloc] init];
            item.key = values.key;
            item.value = values.value;
            item.keyDispName = @"全部";
            [self.secondMenuDatas insertObject:item atIndex:0];
            [item release];
            
            DLog(@"count : %d",self.secondMenuDatas.count);
        }
    }
    else
    {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

#pragma mark - event

//左边barItem
- (void)leftSlideBarItemClickedEvent
{
    if (self.secondMenuShowView && self.secondMenuShowView.isShowOrHide)
    {
        [self.secondMenuShowView dismissPopoverView];
        self.secondMenuShowView.isShowOrHide = NO;
    }
    
    if (self.delegate)
    {
        BOOL slideBarShowflag = [[FMManager sharedInstance] slideBarHideFlag];
        if (slideBarShowflag)
        {
            [self.delegate showSlideBarViwButtonClicked:slideBarShowflag];
            [[FMManager sharedInstance] setSlideBarHideFlagWithBoolValue:NO];
        }
        else
        {
            [self.delegate showSlideBarViwButtonClicked:slideBarShowflag];
            [[FMManager sharedInstance] setSlideBarHideFlagWithBoolValue:YES];
        }
    }
}

//二级目录
- (void)showSecondMenuBtnEvent:(UIButton *)button
{
    if (self.secondMenuShowView && self.secondMenuShowView.isShowOrHide)
    {
        [self.secondMenuShowView dismissPopoverView];
        self.secondMenuShowView.isShowOrHide = NO;
    }
    else
    {
        if (self.secondMenuShowView)
        {
            self.secondMenuShowView = nil;
        }
        
        CGRect rect = CGRectMake(self.view.frame.size.width - 105, 2, 100, 100);
        self.secondMenuShowView = [[[CustomPopoverView alloc] initWithFrame:rect] autorelease];
        self.secondMenuShowView.delegate = self;
        
        self.secondMenuShowView.tableViewDatas = self.secondMenuDatas;
        [self.view addSubview:self.secondMenuShowView];
        [self.view bringSubviewToFront:self.secondMenuShowView];
        
        [self.secondMenuShowView showPopoverView];
        self.secondMenuShowView.isShowOrHide = YES;
        
        DLog(@"new count : %d",self.secondMenuDatas.count);
    }
}

//登录
-(void)editAction:(id)sender
{
    LoginViewController *loginCtrl = [[LoginViewController alloc] init];
    //loginCtrl.delegate = self;
    [loginCtrl initWithStyle:UITableViewStyleGrouped];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginCtrl];
    [loginCtrl release];
    //nav.navigationBar.barStyle = UIBarStyleBlack;
    UIImage *navImage = [UIImage imageNamed:@"top.png"];
    if ([nav.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [nav.navigationBar setBackgroundImage:navImage forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
        UIImageView* imageView = [[[UIImageView alloc] initWithFrame:nav.navigationBar.frame] autorelease];
        imageView.contentMode = UIViewContentModeLeft;
        imageView.image = navImage;
        [nav.navigationBar insertSubview:imageView atIndex:0];
    }
    
    [self.navigationController presentModalViewController:nav animated:YES];
    [nav release];

}

//slideBarDisappearButton
- (void)slideBarDisappearButtonEvent
{
    BOOL slideBarShowflag = [[FMManager sharedInstance] slideBarHideFlag];
    if (!slideBarShowflag && self.delegate)
    {
        [self.delegate showSlideBarViwButtonClicked:slideBarShowflag];
        [[FMManager sharedInstance] setSlideBarHideFlagWithBoolValue:YES];
    }
}

/*
- (void)displayNotification {
    if (self.notify.isAnimating) return;
 
    [self.view addSubview:self.notify];
    [self.notify presentWithDuration:1.8f speed:0.6f inView:self.view completion:^{
        [self.notify removeFromSuperview];
    }];
}

- (BDKNotifyHUD *)notify {
    if (_notify != nil) return _notify;
    
    _notify = [BDKNotifyHUD notifyHUDWithImage:nil text:@"已经没有数据了"];
    
    _notify.center = CGPointMake(self.view.center.x, self.view.center.y - 20);
    DLog(@"%f,%f",_notify.center.x,_notify.center.y);
    return _notify;
}
*/

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([self judgeFirstTitleIsOrNotProductaround])
    {
        return 1;
    }
    else
    {
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self judgeFirstTitleIsOrNotProductaround])
    {
        return self.homeItemArray.count;
    }
    else
    {
        if (section == 0)
        {
            int mol = (self.homeItemArray.count) % kImageIntNums;
            int size = ([self.homeItemArray count])/kImageIntNums + 1;
            if(mol == 0)
            {
                size--;
            }
            return size;
        }
        else
        {
            return 1;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if ([self judgeFirstTitleIsOrNotProductaround])
    {
        static NSString *productAroundCellIdentifier = @"productAroundCellIdentifier";
        ProductAroundCell *cell = [tableView dequeueReusableCellWithIdentifier:productAroundCellIdentifier];
        if (cell == nil)
        {
            cell = [[[ProductAroundCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:productAroundCellIdentifier] autorelease];
        }
        
        NSDictionary *dic = [self.homeItemArray objectAtIndex:indexPath.row];
        [cell.productImageView setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"modelsName"]]];
        
        return cell;
    }
    else
    {
        if (indexPath.section == 0)
        {
            static NSString *threeCellIdentifier3 = @"threeCellIdentifier3";
            ThreeImageCell *cell = [tableView dequeueReusableCellWithIdentifier:threeCellIdentifier3];
            if(cell == nil)
            {
                cell = [[[ThreeImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:threeCellIdentifier3] autorelease];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.contentView.backgroundColor = [UIColor whiteColor];
            }
            
            int row = [indexPath row];
            int index;
            int listSize = [self.homeItemArray count] - 1;
            for( int i = 0; i < kImageIntNums; i++)
            {
                index = row *kImageIntNums +i;
                TouchImageView *imageView = [cell.imageViews objectAtIndex:i];
                
                if (row > 0)
                {
                    CGRect rect = imageView.frame;
                    rect.origin.y = 1.0;
                    imageView.frame = rect;
                }
                
                if(index <= listSize)
                {
                    NSDictionary *dic = [self.homeItemArray objectAtIndex:index];
                    NSString *userId = [dic objectForKey:@"userId"];
                    NSString *modelsAvatarstr = [dic objectForKey:@"modelsAvatarstr"];
                    modelsAvatarstr = [NSString stringWithFormat:@"small_%@",modelsAvatarstr];
                    NSString *imageUrl = [NSString stringWithFormat:@"%@/photo/%@/%@",kHttpHost,userId,modelsAvatarstr];
                    [imageView setImageWithURL:[NSURL URLWithString:imageUrl]
                              placeholderImage:[UIImage imageNamed:@"touxiang.png"]];
                    DLog(@"head url : %@",imageUrl);
                    //[imageView setImage:[UIImage imageNamed:imageUrl]];
                    imageView.delegate = self;
                    imageView.tag = index + 1;
                    imageView.hidden = NO;
                }
                else
                {
                    [imageView setImageWithURL:nil
                              placeholderImage:[UIImage imageNamed:@"touxiang.png"]];
                    imageView.delegate = nil;
                    imageView.hidden = YES;
                }
            }
            return cell;
        }
        else
        {
            if (!self.homeItemArray || self.homeItemArray.count < 1)
            {
                static NSString *threeCellNoDataIdentifier = @"threeCellNoDataIdentifier";
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:threeCellNoDataIdentifier];
                if (cell == nil)
                {
                    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:threeCellNoDataIdentifier] autorelease];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    cell.textLabel.textAlignment = NSTextAlignmentCenter;
                }
                
                return cell;
            }
            else
            {
                static NSString *threeCellHadDataIdentifier = @"threeCellHadDataIdentifier";
                FirstViewPullToGetMoreDataCell *cell = [tableView dequeueReusableCellWithIdentifier:threeCellHadDataIdentifier];
                if(cell == nil)
                {
                    cell = [[[FirstViewPullToGetMoreDataCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:threeCellHadDataIdentifier] autorelease];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    cell.delegate = self;
                }
                
                if (mCurPage == 1 && !mIsLastPage)
                {
                    [cell restoreInitialState];
                }
                
                return cell;
            }
        }
    }
}

#pragma mark - Table view delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self judgeFirstTitleIsOrNotProductaround])
    {
        return 134.0;
    }
    else
    {
        if (indexPath.section == 0)
        {
            float space = (indexPath.row == 1) ? 6.0 : 4.0;
            return ((tableView.frame.size.width - 8) / 3.0 + space);
        }
        else
        {
            return 60.0;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self judgeFirstTitleIsOrNotProductaround])
    {
        NSDictionary *selectedDic = [self.homeItemArray objectAtIndex:indexPath.row];
        NSString *productUrl = [selectedDic objectForKey:@"modelsAvatarstr"];
        ProductShowWebViewController *productWebCtrl = [[[ProductShowWebViewController alloc] init] autorelease];
        productWebCtrl.webUrl = productUrl;
        [self.navigationController pushViewController:productWebCtrl animated:YES];
    }
}

#pragma mark - FirstViewPullToGetMoreDataCellDelegate

- (void)clickedButtonToGetMoreData:(FirstViewPullToGetMoreDataCell *)cutomCell
{
    self.getMoreDataCell = cutomCell;
    
    //点击获取更多数据按钮
    if(!mIsLastPage)
    {
        mIsUpdate = false;
        mCurPage++;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(getKindDatasOfThreeView) userInfo:nil repeats:NO];
    }
    else
    {
        [self.firstTableView.infiniteScrollingView stopAnimating];
    }
}

#pragma mark - event

-(void)viewListing:(id)sender
{
    DLog();
}
-(void)editListing:(id)sender
{
    DLog();
}

#pragma mark - CustomPopoverViewDelegate

- (void)returnChoosedKeyValue:(KeyValueObject *)keyvalue
{
    //根据二级目录刷新当前页面数据
    self.homeItemArray = nil;
    [self.firstTableView reloadData];
    mUserParentId = keyvalue.value;
    mUserSelfId = keyvalue.key;
    mCurPage = 1;
    [self getKindDatasOfThreeView];
    
    [self.secondMenuShowView dismissPopoverView];
    self.secondMenuShowView.isShowOrHide = NO;
}

#pragma mark - TouchImageViewDelegate

-(void) clickImageView:(TouchImageView *) imageView
{
    DLog(@"tag = %d",imageView.tag);
   
    NSDictionary *dic = [self.homeItemArray objectAtIndex:(imageView.tag - 1)];
    NSNumber *numModelId = [dic objectForKey:@"modelsId"];
    NSNumber *userId = [dic objectForKey:@"userId"];
    
    SecondViewController *modelCtrl = [[[SecondViewController alloc] init] autorelease];
    modelCtrl.editType=@"isBrowser";
    modelCtrl.modelId = [NSString stringWithFormat:@"%@",numModelId];
    modelCtrl.userId = [NSString stringWithFormat:@"%@",userId];
    modelCtrl.userIdentify =self.modelTypeFlag;
    
    [self.navigationController pushViewController:modelCtrl animated:YES];
    [modelCtrl myRefeash];
    
    return;
    
    [self becomeFirstResponder];
    
    UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"View" action:@selector(viewListing:)];
    UIMenuItem *menuItem1 = [[UIMenuItem alloc] initWithTitle:@"Edit" action:@selector(editListing:)];
    
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    [menuController setTargetRect:CGRectMake(0, 205, 320, 200) inView:self.firstTableView];
    menuController.menuItems = [NSArray arrayWithObjects:menuItem, menuItem1, nil];
    menuController.arrowDirection = UIMenuControllerArrowDown;
    [menuController setMenuVisible:YES animated:YES];
    
    return;
#if 0
    AGImagePickerController *imagePickerController = [[AGImagePickerController alloc] initWithFailureBlock:^(NSError *error) {
        NSLog(@"Fail. Error: %@", error);
        
        if (error == nil) {
            [self.selectedPhotos removeAllObjects];
            NSLog(@"User has cancelled.");
            [self dismissModalViewControllerAnimated:YES];
        } else {
            
            // We need to wait for the view controller to appear first.
            double delayInSeconds = 0.5;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self dismissModalViewControllerAnimated:YES];
            });
        }
        
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
        
    } andSuccessBlock:^(NSArray *info) {
        [self.selectedPhotos setArray:info];
        
        ALAsset *item = [info objectAtIndex:0];
        NSURL *url = item.defaultRepresentation.url;
        //NSString *uti = item.defaultRepresentation.UTI;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtURL:url error:nil];
        NSLog(@"url = %@",url);
        NSLog(@"Info: %@", info);
        [self dismissModalViewControllerAnimated:YES];
        
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    }];
    
    // Show saved photos on top
    imagePickerController.shouldShowSavedPhotosOnTop = YES;
    imagePickerController.selection = self.selectedPhotos;
    
    // Custom toolbar items
    AGIPCToolbarItem *selectAll = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"全选" style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
        return YES;
    }];
    AGIPCToolbarItem *flexible = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease] andSelectionBlock:nil]; 
    /*
    AGIPCToolbarItem *selectOdd = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"+ Select Odd" style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
        return !(index % 2);
    }];
     */
    AGIPCToolbarItem *deselectAll = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
        return NO;
    }];  
    imagePickerController.toolbarItemsForSelection = [NSArray arrayWithObjects:selectAll, flexible, /*selectOdd, flexible, */deselectAll, nil];
    //    imagePickerController.toolbarItemsForSelection = [NSArray array];
    //[selectOdd release];
    [flexible release];
    [selectAll release];
    [deselectAll release];
    
    //    imagePickerController.maximumNumberOfPhotos = 3;
    [self presentModalViewController:imagePickerController animated:YES];
    [imagePickerController release];
#endif
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFinished:(ASIHTTPRequest *)request
{
    if(mIsUpdate)
    {
        [self.firstTableView.pullToRefreshView stopAnimating];
    }

    NSString *urlStr = [NSString stringWithFormat:@"%@",request.url];
    
    NSString *action = @"";
    if (urlStr.length > 0)
    {
        NSArray *array = [urlStr componentsSeparatedByString:@"/"];
        action = [array objectAtIndex:(array.count - 1)];
    }
    DLog(@"%@",action);
    
    NSData *data = [request responseData];
    NSArray *array = [data objectFromJSONData];
    if(array != nil && array.count > 0)
    {
        NSString *item0 = [array objectAtIndex:0];
        if([item0 isEqualToString:kResponseOk])
        {
            NSDictionary *datadic = [array objectAtIndex:1];
            
            if (mCurPage == 1)
            {
                self.homeItemArray = nil;
            }
            
            if(self.homeItemArray == nil)
            {
                self.homeItemArray = [[[NSMutableArray alloc] init] autorelease];
                mIsLastPage = false;
            }
            
            self.allPageCount = [datadic objectForKey:@"pageCounts"];
            
            
            NSMutableArray *tempArray = [datadic objectForKey:@"data"];
            if(tempArray == nil)
            {
                mIsLastPage = true;
                [self.firstTableView.infiniteScrollingView stopAnimating];
                //[self displayNotification];
                //[FMManager showAlertViewTitle:@"亲" message:@"再也没有数据了"];
                if(mThreeViewHUD == nil)
                {
                    mThreeViewHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                    [self.navigationController.view addSubview:mThreeViewHUD];
                    mThreeViewHUD.delegate = self;
                    [mThreeViewHUD show:YES];
                }
                mThreeViewHUD.mode =MBProgressHUDModeText;
                mThreeViewHUD.labelText = @"再也没有数据了";
                [mThreeViewHUD hide:YES afterDelay:1.5];
                
                if (self.getMoreDataCell)
                {
                    [self.getMoreDataCell stopAnimationOfIndicatorView:NO];
                    self.getMoreDataCell = nil;
                }
                
                return;
            }
            else
            {
                if(tempArray.count == 0)
                {
                    mIsLastPage = true;
                    [self.firstTableView.infiniteScrollingView stopAnimating];
                    //[self displayNotification];
                    //[FMManager showAlertViewTitle:@"亲" message:@"再也没有数据了"];
                    
                    if(mThreeViewHUD)
                    {
                        [mThreeViewHUD removeFromSuperview];
                        [mThreeViewHUD release];
                        mThreeViewHUD = nil;
                    }
                    
                    mThreeViewHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                    [self.navigationController.view addSubview:mThreeViewHUD];
                    mThreeViewHUD.delegate = self;
                    [mThreeViewHUD show:YES];
                
                    mThreeViewHUD.mode =MBProgressHUDModeText;
                    mThreeViewHUD.labelText = @"再也没有数据了";
                    [mThreeViewHUD hide:YES afterDelay:2.5];
                    
                    if (self.getMoreDataCell)
                    {
                        [self.getMoreDataCell stopAnimationOfIndicatorView:NO];
                        self.getMoreDataCell = nil;
                    }
                    
                    return;
                }
                else
                {
                    if(mThreeViewHUD)
                    {
                        mThreeViewHUD.hidden = YES;
                    }
                    
                    for(int i = 0; i< tempArray.count; i++)
                    {
                        //NSMutableDictionary *tempDic = [[[NSMutableDictionary alloc] init] autorelease];
                        NSDictionary *tempDic = [tempArray objectAtIndex:i];
                        
//                        NSString *userId = @"userId";
//                        NSString *modelsAvatarstr = @"modelsAvatarstr";
//                        NSString *modelName = @"modelsName";
//                        [tempDic setObject:[tempItem objectForKey:userId] forKey:userId];
//                        [tempDic setObject:[tempItem objectForKey:modelsAvatarstr] forKey:modelsAvatarstr];
//                        [tempDic setObject:[tempItem objectForKey:modelName] forKey:modelName];
                        [self.homeItemArray addObject:tempDic];
                    }
                }
            }
                           
            /*
            if(self.homeItemArray==nil)
            {
                self.homeItemArray = [datadic objectForKey:@"data"];
                NSLog(@"%@",self.homeItemArray);
            }
            else
            {
                NSMutableArray *array = [datadic objectForKey:@"data"] ;
                NSLog(@"%@",array);
                [self.homeItemArray addObjectsFromArray:array];
            }
             */
            
            if (self.getMoreDataCell)
            {
                [self.getMoreDataCell stopAnimationOfIndicatorView:YES];
                self.getMoreDataCell = nil;
            }
           
            [self.firstTableView reloadData];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    
    //NSError *error = [request error];
    if (1)
    {
        if(mIsUpdate)
        {
            [self.firstTableView.pullToRefreshView stopAnimating];
        }
        
       	// Configure for text only and offset down
        
        if(mThreeViewHUD == nil)
        {
            mThreeViewHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mThreeViewHUD];
            mThreeViewHUD.delegate = self;
            [mThreeViewHUD show:YES];
        }
        mThreeViewHUD.mode =MBProgressHUDModeText;
        mThreeViewHUD.labelText = @"网络链接失败";
        [mThreeViewHUD hide:YES afterDelay:1.5];
    }
    
    if (self.getMoreDataCell)
    {
        [self.getMoreDataCell stopAnimationOfIndicatorView:YES];
        self.getMoreDataCell = nil;
    }
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
	[mThreeViewHUD removeFromSuperview];
	[mThreeViewHUD release];
	mThreeViewHUD = nil;
}

@end